package com.fjrz.bbxwj.main.video

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.os.Bundle
import com.module.lemlin.base.BaseAbstractFragment
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.mode.manager.getDiskCacheDirectoryBitmap
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subscribers.DisposableSubscriber
import kotlinx.android.synthetic.main.fragment_camera_play.*
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception

class CameraPlayFragment : BaseAbstractFragment() {

    companion object {

        private const val EXTRA_NAME_PATH_VIDEO = "EXTRA_NAME_PATH_VIDEO"
        fun newInstance(pathVideo: String): CameraPlayFragment {
            val bundle: Bundle = Bundle().apply {
                putString(EXTRA_NAME_PATH_VIDEO, pathVideo)
            }
            return CameraPlayFragment().apply { arguments = bundle }
        }
    }

    private val mPathVideo: String?
        get() = arguments?.getString(EXTRA_NAME_PATH_VIDEO)

    override val layoutResId: Int
        get() = R.layout.fragment_camera_play

    override fun initView() {


        //视频播放完成回调
        vvCameraVideo.setOnCompletionListener {
            it.start()
            it.isLooping = true
        }
        ivCameraVideoNo.setOnClickListener {
            requireActivity().onBackPressed()
        }
        ivCameraVideoYes.setOnClickListener {
            setFrameBitmapPath()
        }

        startVideoPlay()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        vvCameraVideo.stopPlayback()
    }

    private fun startVideoPlay() {
        vvCameraVideo.setVideoPath(mPathVideo)
        vvCameraVideo.start()
    }

    private fun setFrameBitmapPath() {
        ivCameraVideoYes.isEnabled = false
        Flowable.just((mPathVideo ?: throw Exception("视频地址为空！"))).flatMap({
            val media = MediaMetadataRetriever()
            media.setDataSource(mPathVideo)
            val file = File(
                getDiskCacheDirectoryBitmap(requireContext()).path,
                ("video_${System.currentTimeMillis()}.png")
            )
            val bitmap: Bitmap = media.frameAtTime
                ?: throw Exception("帧图为空！")
            val fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
            fos.flush()
            fos.close()
            return@flatMap Flowable.just(file.path)
        }, { s, s1 -> Path(s, s1) })
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : DisposableSubscriber<Path>() {
                override fun onComplete() = Unit

                override fun onNext(path: Path) {
                    ivCameraVideoYes.isEnabled = true
                    requireActivity().finish()
                    VideoEditingActivity.openEditing(
                        requireActivity(), path.pathVideo, path.pathBitmap
                    )
                }

                override fun onError(t: Throwable) {
                    ivCameraVideoYes.isEnabled = true
                    toast(message = t.message ?: "未知错误")
                }
            })
    }

    data class Path(
        val pathVideo: String,
        val pathBitmap: String
    )

}